package com.easy.work.function;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.base.syslib.util.MessageTools;
import com.base.syslib.util.TextUtil;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.SendValidateCodeRequest;
import com.easy.work.http.request.UpdatePasswordRequest;
import com.easy.work.http.response.ValidateCode;
import com.easy.work.http.response.ValidateCodeEntity;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/18.
 * 重置密码
 */
public class ResetPasswordAct extends BaseActivity {


    public static void start(Context context) {
        Intent intent = new Intent(context, ResetPasswordAct.class);
        context.startActivity(intent);
    }

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_send_verification_code)
    TextView tvSendVerificationCode;
    @BindView(R.id.et_verification_code)
    EditText etVerificationCode;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password_old)
    EditText etPasswordOld;
    @BindView(R.id.btn_upLoad)
    Button btnUpLoad;
    private Timer timer;// 计时器
    private int count = 60;// 记录时间，短信验证60秒内不能再次发送

    /**
     * 验证码
     */
    private String captchaNum;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_reset_password);
        ButterKnife.bind(this);
        initTitle("重置密码");
    }

    @OnClick({R.id.tv_send_verification_code, R.id.btn_upLoad})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_send_verification_code:
                getValidateCode();
                break;
            case R.id.btn_upLoad:
                upLoadPsd();
                break;
        }
    }

    private void upLoadPsd() {
        String password = etPassword.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String estring = "";
        if (TextUtil.isNull(phone)) {
            estring = "请输入手机号";
            MessageTools.showToast(this, estring);
            return;
        }
        if (!TextUtil.isMobile(phone)) {
            estring = "请输入正确的手机号";
            MessageTools.showToast(this, estring);
            return;
        }
        if (TextUtil.isNull(etVerificationCode.getText().toString().trim())) {
            MessageTools.showToast(this, "请输入验证码");
            return;
        }
        if (TextUtil.isNull(password)) {
            MessageTools.showToast(this, "请输入密码");
            return;
        }
        if (password.length() < 6 || password.length() > 12) {
            MessageTools.showToast(this, "密码应该在6—12位");
            return;
        }
        String passwordOld = etPasswordOld.getText().toString().trim();
        if (TextUtil.isNull(passwordOld)) {
            MessageTools.showToast(this, "请再次输入密码");
            return;
        }
        if (!password.equals(passwordOld)) {
            MessageTools.showToast(this, "请输入相同的密码");
            return;
        }

        UpdatePasswordRequest request = new UpdatePasswordRequest();

        String psdMD5 = TextUtil.stringToMD5(password);
        request.loginName = phone;
        request.captchaNum = captchaNum;
        request.newPassword = psdMD5;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(ResetPasswordAct.this, "修改密码成功");
                finish();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(ResetPasswordAct.this, msg);
            }
        });
    }


    /**
     * 获取短信验证码
     */
    private void getValidateCode() {
        int ecolor = Color.RED; // whatever color you want
        String estring = "";
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        String phone = etPhone.getText().toString().trim();
        if (TextUtil.isNull(phone)) {
            estring = "请输入手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etPhone.setError(ssbuilder);
            return;
        }
        if (!TextUtil.isMobile(phone)) {
            estring = "请输入正确的手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etPhone.setError(ssbuilder);
            return;
        }
        count = 60;
        tvSendVerificationCode.setEnabled(false);
        tvSendVerificationCode.setTextColor(Color.parseColor("#949494"));
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(count--);
            }
        }, 0, 1000);

        SendValidateCodeRequest request = new SendValidateCodeRequest();
        request.phone = phone;

        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                ValidateCode entity = (ValidateCode) response;
                captchaNum = entity.captchaNum;
                MessageTools.showToast(getApplicationContext(), "短信验证码发送成功");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(getApplicationContext(), msg);
            }
        });
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                timer.cancel();
                if (tvSendVerificationCode != null) {
                    tvSendVerificationCode.setEnabled(true);
                    tvSendVerificationCode.setTextColor(Color.parseColor("#ffff6c05"));
                    tvSendVerificationCode.setText("获取");
                }
            } else {
                if (tvSendVerificationCode != null) {
                    tvSendVerificationCode.setText(msg.what + "秒");
                }
            }
        }
    };
}
